<template>
  <a-modal
    :title="modalTitle"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
  >
    <div class="allocation-plan-container">
      <!-- 出库单信息 -->
      <a-card title="出库单信息" size="small" style="margin-bottom: 16px">
        <a-row :gutter="16">
          <a-col :span="8">
            <div class="info-item">
              <span class="info-label">出库单号：</span>
              <span class="info-value">{{ outboundInfo.outboundNo || '-' }}</span>
            </div>
          </a-col>
        </a-row>
      </a-card>
      <!-- 分配方案详情 -->
      <a-card title="分配方案详情" size="small">
        <!-- 按出库明细分组显示 -->
        <a-collapse v-if="groupedAllocationPlans.length > 0" :bordered="false">
          <a-collapse-panel
            v-for="(group, index) in groupedAllocationPlans"
            :key="index"
            :header="getGroupHeader(group)"
          >
            <template slot="extra">
              <a-tag :color="getGroupStatusColor(group)">
                {{ getGroupStatusText(group) }}
              </a-tag>
            </template>

            <a-table
              :columns="detailColumns"
              :data-source="group.plans"
              :pagination="false"
              size="small"
              :show-header="false"
              row-key="id"
            >
              <template slot="locationInfo" slot-scope="text, record">
                <div v-if="record">
                  <div>
                    <strong>{{ record.warehouseName || '-' }}</strong>
                  </div>
                  <div style="color: #666; font-size: 12px">{{ record.locationName || '-' }}</div>
                  <div v-if="record.batchNo" style="color: #666; font-size: 12px">批次：{{ record.batchNo }}</div>
                </div>
              </template>

              <template slot="quantityInfo" slot-scope="text, record">
                <div v-if="record">
                  <div>
                    分配：<strong style="color: #1890ff">{{ record.allocationQuantity || 0 }}</strong>
                    {{ record.unit || '' }}
                  </div>
                  <div style="color: #666; font-size: 12px">
                    可用：{{ record.availableQuantity || 0 }} {{ record.unit || '' }}
                  </div>
                </div>
              </template>

              <template slot="status" slot-scope="text, record">
                <a-tag v-if="record" :color="getStatusColor(record.allocationStatus)">
                  {{ getStatusText(record.allocationStatus) }}
                </a-tag>
              </template>
            </a-table>
          </a-collapse-panel>
        </a-collapse>

        <!-- 无分配方案时的提示 -->
        <a-empty v-else description="暂无分配方案" />
      </a-card>

      <!-- 未分配物料提醒 -->
      <a-card
        v-if="unallocatedMaterials && unallocatedMaterials.length > 0"
        title="库存不足物料"
        size="small"
        style="margin-bottom: 16px"
      >
        <a-alert message="以下物料库存不足，请手动创建采购单" type="warning" show-icon style="margin-bottom: 16px" />

        <div style="margin-bottom: 16px; text-align: right">
          <a-button type="primary" @click="showPurchaseList">
            <a-icon type="unordered-list" />
            查看待采购清单
          </a-button>
        </div>

        <a-table
          :columns="unallocatedColumns"
          :dataSource="unallocatedMaterials"
          :pagination="false"
          size="small"
          bordered
          rowKey="materialCode"
        >
          <template slot="shortageQuantity" slot-scope="text, record">
            <span style="color: #ff4d4f; font-weight: bold"> {{ text }} {{ record.unit || '' }} </span>
          </template>

          <template slot="reason">
            <a-tag color="red">库存不足</a-tag>
          </template>
        </a-table>
      </a-card>
    </div>

    <template slot="footer">
      <a-button @click="handleCancel">关闭</a-button>
      <a-button v-if="showReallocateButton" type="primary" ghost @click="handleReallocate" :loading="reallocateLoading">
        重新分配
      </a-button>
      <a-button v-if="summaryData.fullySatisfied" type="primary" @click="handleConfirm" :loading="confirmLoading">
        确认方案
      </a-button>
    </template>
  </a-modal>
</template>

<script>
export default {
  name: 'AllocationPlanModal',
  data() {
    return {
      visible: false,
      confirmLoading: false,
      reallocateLoading: false,
      outboundId: '',
      outboundInfo: {
        outboundNo: '',
      },
      allocationPlans: [],
      allocationResult: {
        success: false,
        fullySatisfied: false,
        allocationPlans: [],
        unallocatedMaterials: [],
        totalRequiredQuantity: 0,
        totalAllocatedQuantity: 0,
        totalUnallocatedQuantity: 0,
        message: '',
      },
      columns: [
        {
          title: '物料信息',
          dataIndex: 'materialInfo',
          width: 200,
          scopedSlots: { customRender: 'materialInfo' },
        },
        {
          title: '库位信息',
          dataIndex: 'locationInfo',
          width: 180,
          scopedSlots: { customRender: 'locationInfo' },
        },
        {
          title: '数量信息',
          dataIndex: 'quantityInfo',
          width: 120,
          scopedSlots: { customRender: 'quantityInfo' },
        },
        {
          title: '分配状态',
          dataIndex: 'allocationStatus',
          width: 100,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '优先级',
          dataIndex: 'priority',
          width: 80,
          align: 'center',
        },
        {
          title: '备注',
          dataIndex: 'remark',
          ellipsis: true,
        },
      ],
      detailColumns: [
        {
          title: '库位信息',
          dataIndex: 'locationInfo',
          width: 200,
          scopedSlots: { customRender: 'locationInfo' },
        },
        {
          title: '数量信息',
          dataIndex: 'quantityInfo',
          width: 150,
          scopedSlots: { customRender: 'quantityInfo' },
        },
        {
          title: '分配状态',
          dataIndex: 'allocationStatus',
          width: 100,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '备注',
          dataIndex: 'remark',
          ellipsis: true,
        },
      ],
      unallocatedMaterials: [],
      selectedUnallocatedKeys: [], // 选中的未分配物料
      generatePurchaseLoading: false, // 生成采购单加载状态
      unallocatedColumns: [
        {
          title: '物料编码',
          dataIndex: 'materialCode',
          width: 120,
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: 150,
        },
        {
          title: '需求数量',
          dataIndex: 'requiredQuantity',
          width: 100,
          align: 'right',
        },
        {
          title: '可用数量',
          dataIndex: 'availableQuantity',
          width: 100,
          align: 'right',
        },
        {
          title: '缺少数量',
          dataIndex: 'shortageQuantity',
          width: 100,
          align: 'right',
          scopedSlots: { customRender: 'shortageQuantity' },
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 60,
        },
        {
          title: '原因',
          width: 80,
          scopedSlots: { customRender: 'reason' },
        },
      ],
    }
  },
  computed: {
    modalTitle() {
      const status = this.summaryData.fullySatisfied ? '完全满足' : '部分满足'
      console.log(this.outboundInfo)
      const outboundNo = this.outboundInfo.outboundNo ? ` - ${this.outboundInfo.outboundNo}` : ''
      return `出库分配方案${outboundNo} - ${status}`
    },
    summaryData() {
      const plans = this.allocationPlans || []
      const totalRequiredQuantity = plans.reduce((sum, plan) => sum + (plan.requiredQuantity || 0), 0)
      const totalAllocatedQuantity = plans.reduce(
        (sum, plan) => sum + (plan.allocatedQuantity || plan.allocationQuantity || 0),
        0
      )
      const totalUnallocatedQuantity = plans.reduce((sum, plan) => sum + (plan.unallocatedQuantity || 0), 0)
      const fullySatisfied = totalUnallocatedQuantity === 0 && totalRequiredQuantity > 0

      return {
        totalRequiredQuantity,
        totalAllocatedQuantity,
        totalUnallocatedQuantity,
        fullySatisfied,
      }
    },
    insufficientMaterials() {
      return this.allocationPlans
        .filter((plan) => {
          const shortage = (plan.requiredQuantity || 0) - (plan.allocatedQuantity || plan.allocationQuantity || 0)
          return shortage > 0
        })
        .map((plan) => ({
          ...plan,
          shortageQuantity: (plan.requiredQuantity || 0) - (plan.allocatedQuantity || plan.allocationQuantity || 0),
        }))
    },
    showReallocateButton() {
      return this.outboundId && this.allocationPlans.length > 0
    },
    groupedAllocationPlans() {
      // 按物料编号分组
      const groups = {}
      this.allocationPlans.forEach((plan) => {
        const key = plan.materialCode
        if (!groups[key]) {
          groups[key] = {
            materialCode: plan.materialCode,
            materialName: plan.materialName,
            materialType: plan.materialType,
            specification: plan.specification,
            color: plan.color,
            unit: plan.unit,
            requiredQuantity: plan.requiredQuantity || 0,
            plans: [],
          }
        }
        groups[key].plans.push(plan)
      })

      return Object.values(groups)
    },
  },
  methods: {
    show(outboundId, allocationData) {
      this.outboundId = outboundId
      this.allocationResult = {}
      this.allocationPlans = []
      this.unallocatedMaterials = []
      this.outboundInfo = {
        outboundNo: '',
        warehouseName: '',
        createTime: '',
      }

      // 处理不同的数据格式
      if (Array.isArray(allocationData)) {
        // 如果是数组格式（来自API的直接响应）
        this.allocationPlans = allocationData
        this.unallocatedMaterials = []
        // 从第一条记录中提取出库单信息
        if (allocationData.length > 0) {
          const firstRecord = allocationData[0]
          this.outboundInfo = {
            outboundNo: firstRecord.outboundNo || firstRecord.outbound_no || '',
            warehouseName: firstRecord.warehouseName || firstRecord.warehouse_name || '',
            createTime: firstRecord.createTime || firstRecord.create_time || '',
          }
        }
      } else if (allocationData) {
        // 如果是对象格式（包含分配结果和未分配物料）
        this.allocationResult = allocationData
        this.allocationPlans = allocationData.allocationPlans || []
        this.unallocatedMaterials = (allocationData.unallocatedMaterials || []).map((material) => ({
          ...material,
          purchaseQuantity: material.shortageQuantity, // 初始化采购数量为缺少数量
        }))
        this.outboundInfo = {
          outboundNo: allocationData.outboundNo || allocationData.outbound_no || '',
          warehouseName: allocationData.warehouseName || allocationData.warehouse_name || '',
          createTime: allocationData.createTime || allocationData.create_time || '',
        }
      }

      // 如果还是没有出库单号，尝试通过outboundId获取
      if (!this.outboundInfo.outboundNo && outboundId) {
        this.loadOutboundInfo(outboundId)
      }

      this.visible = true
    },

    // 新增方法：通过ID获取出库单信息
    loadOutboundInfo(outboundId) {
      this.$http
        .get('/wms/outbound/queryById', {
          params: { id: outboundId },
        })
        .then((res) => {
          if (res.success && res.result) {
            this.outboundInfo = {
              outboundNo: res.result.outboundNo || '',
              warehouseName: res.result.warehouseName || '',
              createTime: res.result.createTime || '',
            }
          }
        })
        .catch((err) => {
          console.error('获取出库单信息失败:', err)
        })
    },

    hide() {
      this.visible = false
      this.confirmLoading = false
      this.reallocateLoading = false
      this.unallocatedMaterials = []
      this.selectedUnallocatedKeys = []
      this.generatePurchaseLoading = false
    },

    // 未分配物料选择变化
    onUnallocatedSelectionChange(selectedRowKeys, selectedRows) {
      this.selectedUnallocatedKeys = selectedRowKeys
    },

    // 采购数量变化处理
    handlePurchaseQuantityChange(record, value) {
      record.purchaseQuantity = value || record.shortageQuantity
    },

    // 显示采购清单
    showPurchaseList() {
      this.$info({
        title: '采购清单',
        content: this.renderPurchaseListContent(),
        width: 600,
        okText: '知道了',
        onOk: () => {
          // 可以在这里添加跳转到采购模块的逻辑
          this.$message.info('请前往采购管理模块创建采购单')
        },
      })
    },

    // 渲染采购清单内容
    renderPurchaseListContent() {
      const h = this.$createElement
      const materials = this.unallocatedMaterials

      return h('div', [
        h('p', { style: { marginBottom: '16px', fontSize: '14px' } }, '以下物料库存不足，需要采购：'),
        h(
          'ul',
          { style: { marginBottom: '16px', paddingLeft: '20px' } },
          materials.map((material) =>
            h(
              'li',
              { style: { marginBottom: '8px', fontSize: '13px' } },
              `${material.materialName}(${material.materialCode}) - 缺少数量: ${material.shortageQuantity} ${
                material.unit || ''
              }`
            )
          )
        ),
        h(
          'div',
          { style: { padding: '12px', backgroundColor: '#f6ffed', border: '1px solid #b7eb8f', borderRadius: '6px' } },
          [
            h(
              'p',
              { style: { margin: '0', fontSize: '13px', color: '#52c41a' } },
              '💡 提示：请前往【采购管理】模块手动创建采购单'
            ),
          ]
        ),
      ])
    },

    // 根据物料类型推荐仓库ID
    getRecommendedWarehouseId(materialType) {
      // 这里可以根据实际的仓库配置来映射
      const warehouseTypeMap = {
        1: 1, // 型材 -> 型材库
        2: 2, // 配件 -> 配件库
        3: 3, // 辅件 -> 辅件库
        4: 4, // 其他 -> 其他库
        5: 5, // 余料 -> 余料库
        6: 6, // 半料 -> 半料库
      }
      return warehouseTypeMap[materialType] || 4 // 默认其他库
    },

    handleOk() {
      this.handleConfirm()
    },

    handleCancel() {
      this.hide()
    },

    handleConfirm() {
      if (!this.summaryData.fullySatisfied) {
        this.$confirm({
          title: '确认分配方案',
          content: '当前分配方案无法完全满足出库需求，是否确认使用此方案？',
          onOk: () => {
            this.confirmAllocation()
          },
        })
      } else {
        this.confirmAllocation()
      }
    },

    confirmAllocation() {
      this.confirmLoading = true
      // 这里可以添加确认分配方案的逻辑
      setTimeout(() => {
        this.$message.success('分配方案已确认')
        this.confirmLoading = false
        this.hide()
        this.$emit('confirmed', { allocationPlans: this.allocationPlans, summaryData: this.summaryData })
      }, 1000)
    },

    handleReallocate() {
      this.reallocateLoading = true
      this.$http
        .post('/wms/outbound/reallocate', null, {
          params: { outboundId: this.outboundId },
        })
        .then((res) => {
          if (res.success) {
            // 处理重新分配的结果
            if (Array.isArray(res.result)) {
              this.allocationPlans = res.result
            } else {
              this.allocationResult = res.result
              this.allocationPlans = (res.result && res.result.allocationPlans) || []
            }
            this.$message.success('重新分配成功')
            this.$emit('reallocated', { allocationPlans: this.allocationPlans, summaryData: this.summaryData })
          } else {
            this.$message.error(res.message || '重新分配失败')
          }
        })
        .catch((err) => {
          console.error('重新分配失败:', err)
          this.$message.error('重新分配失败')
        })
        .finally(() => {
          this.reallocateLoading = false
        })
    },

    getStatusColor(status) {
      const colorMap = {
        0: 'default', // 待分配
        1: 'green', // 已分配
        2: 'orange', // 部分分配
      }
      return colorMap[status] || 'default'
    },

    getStatusText(status) {
      const textMap = {
        0: '待分配',
        1: '已分配',
        2: '部分分配',
      }
      return textMap[status] || '未知'
    },

    // 获取分组标题
    getGroupHeader(group) {
      const allocatedQuantity = group.plans.reduce((sum, plan) => sum + (plan.allocationQuantity || 0), 0)
      const shortageQuantity = Math.max(0, group.requiredQuantity - allocatedQuantity)

      let header = `${group.materialName} (${group.materialCode})`
      if (group.specification) {
        header += ` - ${group.specification}`
      }
      if (group.color) {
        header += ` - ${group.color}`
      }
      header += ` | 需求: ${group.requiredQuantity} ${group.unit || ''}, 已分配: ${allocatedQuantity} ${
        group.unit || ''
      }`

      if (shortageQuantity > 0) {
        header += `, 缺少: ${shortageQuantity} ${group.unit || ''}`
      }

      return header
    },

    // 获取分组状态颜色
    getGroupStatusColor(group) {
      const allocatedQuantity = group.plans.reduce((sum, plan) => sum + (plan.allocationQuantity || 0), 0)
      const shortageQuantity = group.requiredQuantity - allocatedQuantity

      if (shortageQuantity <= 0) {
        return 'green' // 完全满足
      } else if (allocatedQuantity > 0) {
        return 'orange' // 部分满足
      } else {
        return 'red' // 未分配
      }
    },

    // 获取分组状态文本
    getGroupStatusText(group) {
      const allocatedQuantity = group.plans.reduce((sum, plan) => sum + (plan.allocationQuantity || 0), 0)
      const shortageQuantity = group.requiredQuantity - allocatedQuantity

      if (shortageQuantity <= 0) {
        return '完全满足'
      } else if (allocatedQuantity > 0) {
        return '部分满足'
      } else {
        return '未分配'
      }
    },
  },
}
</script>

<style scoped>
.allocation-plan-container {
  max-height: 70vh;
  overflow-y: auto;
}

.ant-statistic {
  text-align: center;
}

.ant-table-tbody > tr > td {
  padding: 8px;
}

.ant-card-head {
  min-height: 40px;
}

.ant-card-head-title {
  padding: 8px 0;
  font-size: 14px;
}

.ant-card-body {
  padding: 12px;
}

.info-item {
  margin-bottom: 8px;
}

.info-label {
  color: #666;
  font-size: 14px;
}

.info-value {
  color: #333;
  font-weight: 500;
  margin-left: 4px;
}
</style>
